#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 710;
int a[N][N];
bool st[N][N];
int dx[8] = { 1,-1,0,0,1,1,-1,-1 };
int dy[8] = { 0,0,1,-1,-1,1,1,-1 };
int n, m;
struct node
{
	int val;
	int x, y;
}S[N*N];

int cmp(node a, node b)
{
	return a.val > b.val;
}

void dfs(int x, int y)
{
	st[x][y] = 1;
	for (int i = 0; i < 8; i++) {
		int x1 = x + dx[i];
		int y1 = y + dy[i];
		if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && !st[x1][y1] && a[x1][y1] <= a[x][y]) {
			dfs(x1, y1);
		}
	}
}
int main()
{
	cin >> n >> m;
	int cnt = 0;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
			S[++cnt] = { a[i][j],i,j };
		}
	}
	int ans = 0;
	sort(S + 1, S + cnt + 1, cmp);
	for (int i = 1; i <= n * m; i++) {
		//cout << "S[i].val==" << S[i].val << endl;
		if (!st[S[i].x][S[i].y]) {
			bool flag = 0;
			for (int j = 0; j < 8; j++) {
				int x = S[i].x + dx[j];
				int y = S[i].y + dy[j];
				if (a[x][y] > S[i].val) {
					flag = 1;
					break;
				}
			}
			if (!flag) {
				//cout << "S[i].x==" << S[i].x << endl;
				//cout << "S[i].y==" << S[i].y << endl;
				dfs(S[i].x, S[i].y);
				ans++;
			}
		}
	}
	/*for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << st[i][j] << " ";
		}
		cout << endl;
	}*/
	cout << ans << endl;
	return 0;
}